import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken, getVersionType } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 15000 // request timeout
})

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (store.getters.token) {
    config.headers['accessToken'] = getToken()
    config.headers['versionType'] = getVersionType()
  }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
// response => response.data,
  response => {
    const res = response.data
    if (res.code && (res.code === 110)) {
      store.dispatch('LogOut').then(() => {
        location.reload()// In order to re-instantiate the vue-router object to avoid bugs
      })
    }
    if (res.code && (res.code === 102 || res.code === 103)) {
      Message({
        message: res.msg,
        type: 'error',
        duration: 5 * 1000
      })
      // return Promise.reject('error')
      return Promise.resolve({
        isError: true,
        errorMsg: res.msg,
        isNetError: false
      })
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error)// for debug
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    return Promise.resolve({
      isError: true,
      errorMsg: error.message,
      isNetError: true
    })
  }
)

export default service
